package com.ruoyi.common.core.utils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectionUtils {
    /**
     * 转化
     */
    public static  <T, R> List<R> toList(List<T> list, Function<? super T, ? extends R> mapper){
        return list.stream().map(mapper).collect(Collectors.toList());
    }

    /**
     * 分组
     */
    public static  <T, K> Map<K, List<T>> group(List<T> list, Function<? super T, ? extends K> classifier){
        return list.stream().collect(Collectors.groupingBy(classifier));
    }

    /**
     * List转map
     */
    public static <T, K, U>  Map<K,U> toMap(List<T> list, Function<? super T, ? extends K> keyMapper,
                                            Function<? super T, ? extends U> valueMapper){
        return list.stream().collect(Collectors.toMap(keyMapper, valueMapper,(k1,k2)-> k2));
    }
    /**
     * 判断是否包含
     */
    public static <T> boolean contants(Collection<T> collection,T t) {
        boolean empty = isEmpty(collection);
        if (empty){
            return false;
        }
        return collection.contains(t);
    }

    /**
     * 判断集合长度是否等于0
     */
    public static boolean isEmpty(Collection<?> collection) {

        return collection == null || collection.isEmpty();
    }

    /**
     * 判断集合长度是否大于0
     */
    public static boolean isNotEmpty(Collection<?> collection) {
        return !isEmpty(collection);
    }

    /**
     * 判断集合不等于空且长度等于指定大小
     */
    public static boolean isNotEmptyAndSize(Collection<?> collection,int size) {
        return isNotEmpty(collection) && collection.size()==size;
    }

    /**
     * 判断集合长度是否等于0
     */
    public static boolean isEmpty(Map<?,?> map) {
        return map == null || map.isEmpty();
    }

    /**
     * 判断集合长度是否等于0
     */
    public static boolean isNotEmpty(Map map) {
        return !isEmpty(map);
    }

    /**
     *  创建空集合
     */
    public static <T> List<T> empty(){
        return new ArrayList<T>();
    }

    /**
     * 正序排序
     */
    public static <T, U extends Comparable<? super U>> List<T> asc(
            List<T> list,  Function<? super T, ? extends U> keyExtractor){
        return list.stream().sorted(Comparator.comparing(keyExtractor)).collect(Collectors.toList());
    }

    /**
     * 正序排序
     */
    public static <T, U extends Comparable<? super U>> List<T> desc(
            List<T> list,  Function<? super T, ? extends U> keyExtractor){
        return list.stream().sorted(Comparator.comparing(keyExtractor).reversed()).collect(Collectors.toList());
    }

    /**
     * 正序排序
     */
    public static <T, U extends Comparable<? super U>> List<T> desc(
            Stream<T> stream, Function<? super T, ? extends U> keyExtractor){
        return stream.sorted(Comparator.comparing(keyExtractor).reversed()).collect(Collectors.toList());
    }
}
